#include "extension.h"
#include <QJsonValue>
#include <QTimer>

namespace yc {

Extension::Extension(ExtensionManager* ext_mgr, QWidget* container)
    : QObject(nullptr),
      ext_mgr_(ext_mgr),
      forced_stop_(false),
      stop_delay_(0),
      stopping_(false),
      stop_timer_(nullptr)
{
    Q_UNUSED(container)
}

Extension::~Extension() { }

bool Extension::start(const QString& args)
{
    Q_UNUSED(args)
    return true;
}

void Extension::requestStop()
{
    internalStop(false);
}

void Extension::stop()
{
    internalStop(true);
}

QJsonValue Extension::saveState() const
{
    return QJsonValue();
}

void Extension::restoreState(const QJsonValue& state)
{
    Q_UNUSED(state)
}

void Extension::cancelStop()
{
    if (stopping_) {
        stopping_ = false;
        if (stop_timer_) {
            stop_timer_->stop();
        }
        Q_EMIT stopIgnored();
    }
}

void Extension::stopStopTimer()
{
    if (stopping_ && stop_timer_) {
        stop_timer_->stop();
    }
}

void Extension::restoreStopTimer()
{
    if (stopping_ && stop_timer_) {
        stop_timer_->start(stop_delay_);
    }
}

void Extension::internalStop(bool forced_stop, int delay)
{
    if (!stopping_) {
        forced_stop_ = forced_stop;
        stop_delay_ = delay;
        Q_EMIT aboutToStop();
        if (delay > 0) {
            stopping_ = true;
            if (!stop_timer_) {
                stop_timer_ = new QTimer(this);
                stop_timer_->setInterval(delay);
                stop_timer_->setSingleShot(true);
                connect(stop_timer_, &QTimer::timeout, this, [this] {
                    if (stopping_) {
                        Q_EMIT stopped();
                    }
                });
            }
            stop_timer_->start(delay);
        } else {
            Q_EMIT stopped();
        }
    }
}

} // namespace yc
